package org.validation;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UserValidator {

	private static final int LOGIN_MIN = 3;
	private static final int LOGIN_MAX = 20;
	private static final int PASS_MIN = 6;
	private static final int PASS_MAX = 20;
	private static final int MAIL_MAX = 45;
	
	public static boolean isLoginValid(String login) {
		boolean valid = true;
		valid &= Expression.isRegular(login);
		valid &= login.length() >= LOGIN_MIN;
		valid &= login.length() <= LOGIN_MAX;
		return valid;
	}
		
	public static boolean isPasswordValid(String pass) {
		
		boolean valid = true;
		valid &= Expression.isRegular(pass);
		valid &= pass.length() >= PASS_MIN;
		valid &= pass.length() <= PASS_MAX;
		valid &= containsNumber(pass);
		return valid;
	}
	
	public static boolean isMailValid(String mail) {
		
		if(mail.length() > MAIL_MAX) return false;
		
		int i = mail.indexOf('@');
		if(i < 0) return false;
		
		String str = mail.substring(0, i-1);
		if(str.indexOf('.') == 0) return false;
		if(!Expression.isRegular(str)) return false;
		
		str = mail.substring(i+1, mail.length());
		if(str.indexOf('.') == 0) return false;
		if(str.endsWith(".")) return false;
		if(!Expression.isRegular(str) || !str.contains(".")) return false;
		
		return true;
	}
	
	
	
	private static boolean containsNumber(String string) {
		
		Pattern p = Pattern.compile("[0-9]", Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(string);
		return m.find();
	}
	
	private static class Expression {

		public static boolean isValid(String str, int max, int min) {
			if(str == null) return false;
			boolean valid = true;
			valid &= Expression.isRegular(str);
			valid &= str.length() <= max;
			valid &= str.length() >= min;
			return valid;
		}
		
		public static boolean isRegular(String string) {
			
			if(string == null) return false;
			Pattern p = Pattern.compile("[^a-z0-9 .,!?]", Pattern.CASE_INSENSITIVE);
			Matcher m = p.matcher(string);
			return !m.find();
		}
	}
}
